package com.zdc.learn.netty.rpc.client;

import com.zdc.learn.netty.rpc.service.HelloService;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

import java.lang.reflect.Proxy;
import java.util.concurrent.ExecutorService;

import static java.util.concurrent.Executors.newFixedThreadPool;

public class RpcNettyClient {

    private ExecutorService executorService = newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    private static RpcNettyClientHandler client;

    public Object getBean(final Class<?> serviceClass,final String providerName){
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),new Class<?>[]{serviceClass},((proxy, method, args) -> {
            if (client == null){
                init();
            }
            client.setPara(providerName+args[0]);
            return executorService.submit(client).get();
        }));
    }

    public void init(){
        client = new RpcNettyClientHandler();
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
                    pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
                    pipeline.addLast(client);
                }
            });

            ChannelFuture future = bootstrap.connect("127.0.0.1", 6666).sync();
        }catch (Exception e){
            group.shutdownGracefully();
        }finally {

        }


    }

    public static void main(String[] args) {
        RpcNettyClient rpcNettyClient = new RpcNettyClient();
        HelloService helloService = (HelloService)rpcNettyClient.getBean(HelloService.class, "HelloService#hello#");

        String re = helloService.hello("hello world");
        System.out.println("re:"+re);
    }
}
